﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class AchievementListCell : MonoBehaviour
{
    // 업적셀 프리펩
    static GameObject s_ListCellPrefab;
    // 업적셀 프리펩 리소스 위치
    const string CellPrefabPath = "Prefabs/Achievement/AchievementListCell";
    // 업적 정보
    static IDictionary<int, CAchievementData> s_AchievementDataDic;
    static int[] s_SortedKeys;

    // 업적 이름 및 달성카운트 및 보상여부
    public UILabel m_AchievementNameLabel;
    public UILabel m_AchievementCountLabel;
    public UILabel m_AchievementCompleteLabel;
    public UILabel m_AchievementUpdateLabel;

    CAchievementData m_AchievementData;
    AchievementInfo m_AchievementInfo;
    int m_CellIndex = -1;

    bool m_IsComplete = false;
    bool m_IsCanReward = false;

    static public AchievementListCell SetCell(int index, Transform parent, UIScrollView scrollView)
    {
        if (s_ListCellPrefab == null)
            s_ListCellPrefab = Resources.Load(CellPrefabPath) as GameObject;

        if (s_AchievementDataDic == null)
        {
            s_AchievementDataDic = CAchievementDataManager.Instance.GetAchievementMap();

            ICollection<int> temp = s_AchievementDataDic.Keys;

            s_SortedKeys = new int[temp.Count];
            temp.CopyTo(s_SortedKeys, 0);
            Array.Sort(s_SortedKeys);
        }

        GameObject tempOBJ = Instantiate(s_ListCellPrefab) as GameObject;

        tempOBJ.transform.parent = parent;
        tempOBJ.transform.localPosition = new Vector3(0, -50 - (index * 75), 0);
        tempOBJ.transform.localScale = Vector3.one;


        UIDragScrollView tempDS = tempOBJ.GetComponent("UIDragScrollView") as UIDragScrollView;
        tempDS.scrollView = scrollView;


        AchievementListCell tempAC = tempOBJ.GetComponent("AchievementListCell") as AchievementListCell;

        return tempAC;
    }


    public void SetCellWithIndex(int index)    // index 몇번째 인지
    {
        m_CellIndex = index;

        int logName_index = -1; // 같은 로그 하나로 계산
        LogCounterType preLogName = LogCounterType.NONE;

        int tempID = 0;
        int useIndex = 0;

        for (int i = 0; i < s_SortedKeys.Length; i++)
        {
            tempID = s_SortedKeys[i];

            if (s_AchievementDataDic[tempID].achieve_type != achieve_type.achievement)  // 어치브먼트 아닐때 패스
                continue;

            if (s_AchievementDataDic[tempID].log_name.CompareTo(preLogName) != 0)  // 이전 어치브 먼트 로그네임과 같이 않을때
            {
                logName_index++; // 다음 아이디로 진행
                preLogName = s_AchievementDataDic[tempID].log_name;
            }

            if (index == logName_index)  // 해당 로그네임 일때
            {
                useIndex = i;
                break;
            }
        }

        while (true)
        {
            m_AchievementData = s_AchievementDataDic[tempID];

            m_IsComplete = false;
            m_IsCanReward = false;

            foreach (AchievementInfo tempInfo in MyInfo.Instance.AchievementList)
            {
                if (tempInfo.achievementId == tempID)
                {
                    if (tempInfo.achievementLevel == 0)     // 어치브 달성 못함
                        break;

                    m_IsComplete = true;
                    m_IsCanReward = !tempInfo.isReward;

                    m_AchievementInfo = tempInfo;   // 해당
                    break;
                }
            }

            bool needNext = false;  // 다음단계로 이동해야 하는지 다음 단계가 존재하는지
            if (m_IsComplete && !m_IsCanReward)  // 완료했고 보상 받았으면 다음 단계 표시
            {
                if (useIndex + 1 < s_SortedKeys.Length) // 다음단계 있는지
                {
                    if (s_AchievementDataDic[s_SortedKeys[useIndex + 1]].log_name == preLogName) // 다음단계가 지금 로그네임과 같은지                            
                        needNext = true;                                            
                }
            }

            if (needNext)
            {
                tempID = s_SortedKeys[useIndex + 1];
                useIndex++;
            }
            else   // UI설정
            {
                int achievementCount = 0;

                foreach (AchievementValue tempValue in MyInfo.Instance.AchievementValueList)
                {
                    if (tempValue.achievementLogname == (int)m_AchievementData.log_name)
                    {
                        achievementCount = tempValue.achievementData;
                        break;
                    }
                }

                BoxCollider coll = m_AchievementCompleteLabel.GetComponent("BoxCollider") as BoxCollider;
                UIButtonMessage tempBM = m_AchievementCompleteLabel.GetComponent("UIButtonMessage") as UIButtonMessage;

                if (m_IsComplete)
                {
                    if (m_IsCanReward)
                        m_AchievementCompleteLabel.text = "보상받기";
                    else
                        m_AchievementCompleteLabel.text = "완료";

                    tempBM.target = gameObject;
                    tempBM.functionName = "OnRewardButton";

                    coll.enabled = m_IsCanReward;
                }
                else
                {
                    m_AchievementCompleteLabel.text = "진행중";

                    tempBM.target = gameObject;
                    tempBM.functionName = "";

                    coll.enabled = false;
                }

                m_AchievementNameLabel.text = m_AchievementData.title_body;
                m_AchievementUpdateLabel.text = "";
                m_AchievementCountLabel.text = string.Format("{0} / {1}", achievementCount, m_AchievementData.log_count);

                break;
            }
        }
    }

    public void SetCellWithIndex2(int index)  // 이전 함수 사용 (x)
    {
        m_CellIndex = index;

        int i = -1; // 같은 로그 하나로 계산

        LogCounterType preLogName = LogCounterType.NONE;
        foreach (int tempID in s_SortedKeys)
        {
            if (s_AchievementDataDic[tempID].achieve_type != achieve_type.achievement)  // 어치브먼트 아닐때 패스
                continue;

            if (s_AchievementDataDic[tempID].log_name.CompareTo(preLogName) != 0)
            {
                i++;
                preLogName = s_AchievementDataDic[tempID].log_name;
            }

            if (index == i)
            {
                m_AchievementData = s_AchievementDataDic[tempID];
                m_AchievementNameLabel.text = m_AchievementData.title_body;

                m_IsComplete = false;
                m_IsCanReward = false;

                int achievementCount = 0;

                foreach (AchievementValue tempValue in MyInfo.Instance.AchievementValueList)
                {
                    if (tempValue.achievementLogname == (int)m_AchievementData.log_name)
                    {
                        achievementCount = tempValue.achievementData;
                        break;
                    }
                }

                foreach (AchievementInfo tempInfo in MyInfo.Instance.AchievementList)
                {
                    if (tempInfo.achievementId == tempID)
                    {
                        m_AchievementInfo = tempInfo;                        
                            //tempInfo.achievementLevel.ToString();

                        if (tempInfo.achievementLevel == 0)     // 어치브 달성 못함
                            break;

                        //m_AchievementUpdateLabel.text = string.Format("update = {0}", tempInfo.updateTime.ToShortTimeString());
                       
                        m_IsComplete = true;
                        m_IsCanReward = !tempInfo.isReward;
                        break;
                    }
                }

                BoxCollider coll = m_AchievementCompleteLabel.GetComponent("BoxCollider") as BoxCollider;
                UIButtonMessage tempBM = m_AchievementCompleteLabel.GetComponent("UIButtonMessage") as UIButtonMessage;

                if (m_IsComplete)
                {
                    if (m_IsCanReward)
                        m_AchievementCompleteLabel.text = "보상받기";
                    else
                        m_AchievementCompleteLabel.text = "완료";

                    tempBM.target = gameObject;
                    tempBM.functionName = "OnRewardButton";

                    coll.enabled = m_IsCanReward;
                }
                else
                {
                    m_AchievementCompleteLabel.text = "진행중";

                    tempBM.target = gameObject;
                    tempBM.functionName = "";

                    coll.enabled = false;
                }

                m_AchievementUpdateLabel.text = "";                
                m_AchievementCountLabel.text = string.Format("{0} / {1}", achievementCount, m_AchievementData.log_count);
                
                break;
            }
        }
    }

    void OnRewardButton(GameObject button)
    {
        LoadingWindow.window.ShowShortLoading();        
        RestAPI.singleton.GetMyAchievementReward(CallbackOfGetMyAchievementReward, m_AchievementData.id);
    }

    void CallbackOfGetMyAchievementReward(Hashtable returnData)
    {
        LoadingWindow.window.HideLoading();
        m_AchievementInfo.isReward = true;
        SetCellWithIndex(m_CellIndex);

        int rewardType = 0;  // 1 골드 2 다이아몬드

        if (m_AchievementData.reward_01.Contains("gold"))       
            rewardType = 1;
        else if (m_AchievementData.reward_01.Contains("diamond"))       
            rewardType = 2;
            

        int delIndex = m_AchievementData.reward_01.IndexOf(" ");
        Debug.LogError("delIndex ------------ " + delIndex);
        string valueString = m_AchievementData.reward_01.Remove(0, delIndex + 1);

        int value = int.Parse(valueString);
        Debug.LogError("value ------------ " + value);
        switch (rewardType)
        {
            case 1:
                MyInfo.Instance.Money += value;

                break;
            case 2:
                MyInfo.Instance.Diamond += value;
                break;
            //case 3:
            //    break;
        }
    }
}
